package com.aynu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.aynu.common.to.es.SKUEsModel;
import com.aynu.common.utils.R;
import com.aynu.gulimall.search.config.ElasticSearchConfig;
import com.aynu.gulimall.search.constant.EsConstant;
import com.aynu.gulimall.search.feign.ProductFeignService;
import com.aynu.gulimall.search.service.MallSearchService;
import com.aynu.gulimall.search.vo.AttrRespVo;
import com.aynu.gulimall.search.vo.BrandVo;
import com.aynu.gulimall.search.vo.SearchParam;
import com.aynu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author mj
 * @version 1.0
 * @date 2021/3/11 19:41
 */
@Service
@Slf4j
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public SearchResult search(SearchParam param) {
        //1 动态构建出DSL语句
        SearchRequest searchRequest = builderSearchRequest(param);

        SearchResult searchResult = null;
        SearchResponse response = null;
        try {
            //2 执行检索请求
            response = client.search(searchRequest, ElasticSearchConfig.COMMON_OPTIONS);
        } catch (Exception e) {
            log.error("es查询出错,{}", e);
            e.printStackTrace();
        }

        try {
            //3 响应数据数据,封装成我们需要的格式
            searchResult = builderSearchResult(response, param);
        } catch (Exception e) {
            log.error("解析es返回信息出错,{}", e);
            e.printStackTrace();
        }

        return searchResult;
    }

    private SearchRequest builderSearchRequest(SearchParam param) {
        //模糊匹配，过滤（按照属性、分类、价格区间、库），排序，分类，高亮，聚合分析

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //1 添加查询条件
        addSearchParam(param, sourceBuilder);

        //2.1 添加排序
        searchSort(param, sourceBuilder);

        //2.2 添加分页
        if (param.getPageNum() != null) {
            sourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
            sourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);
        }

        //2.3 添加高亮显示
        addSearchHighlight(param, sourceBuilder);

        //3 添加聚合分析
        addSearchAggregation(sourceBuilder);


        String string = sourceBuilder.toString();
        System.out.println("dsl: " + string);

        return new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, sourceBuilder);
    }

    private SearchResult builderSearchResult(SearchResponse response, SearchParam param) {
        //创建返回实例
        SearchResult result = new SearchResult();
        //获取hits对象（所有信息都在这里面封装）
        SearchHits hits = response.getHits();

        //1、返回的商品信息
        respAddProduct(result, hits, param);

        //2、当前所有商品涉及的所有属性信息
        respAddAttr(response, result);

        //3、当前所有商品涉及到的所有品牌信息
        respAddBrand(response, result);

        //4、当前所有商品涉及到的分类信息
        respAddCatalog(response, result);

        //以上聚合分析后得到的信息

        //5、分页信息-总信息数
        long total = hits.getTotalHits().value;
        result.setTotal(total);
        //6、总页码
        int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE) + 1;
        result.setTotalPage(totalPages);
        //设置当前页
        result.setPageNum(param.getPageNum());

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= totalPages; i++) {
            pageNavs.add(i);
        }
        result.setTotalNavs(pageNavs);

        //构建规格属性面包屑导航
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            List<SearchResult.NavVo> collect = param.getAttrs().stream().map(attr -> {
                SearchResult.NavVo navVo = new SearchResult.NavVo();

                String[] attrValues = attr.split("_");
                navVo.setNavValue(attrValues[1]);

                R r = productFeignService.info(Long.parseLong(attrValues[0]));
                result.getAttrIds().add(Long.parseLong(attrValues[0]));
                if (r.getCode() == 0) {
                    AttrRespVo attrRespVo = r.getData("attr", new TypeReference<AttrRespVo>() {
                    });
                    navVo.setNavName(attrRespVo.getAttrName());
                } else {
                    navVo.setNavName("");
                }

                //2、取消了这个面包屑以后，我们要跳转到哪个地方，将请求地址的url里面的当前地址清空
                //拿到所有的查询条件，去掉当前的
                String link = replaceQueryString(param, attr,"attrs");
                navVo.setLink("http://search.gulimall.com/list.html?" + link);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(collect);
        }

        if (!CollectionUtils.isEmpty(param.getBrandId())) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();
            navVo.setNavName("品牌");
            //TODO 远程查询所有品牌
            R r = productFeignService.brandInfo(param.getBrandId());
            if (r.getCode() == 0) {
                List<BrandVo> brandVos = r.getData("brand", new TypeReference<List<BrandVo>>() {
                });
                String link = "";
                StringBuilder builder = new StringBuilder();
                for (BrandVo brandVo : brandVos) {
                    builder.append(brandVo.getName()).append(";");
                    link = replaceQueryString(param, brandVo.getBrandId()+"","brandId");
                }
                navVo.setNavValue(builder.toString());
                navVo.setLink("http://search.gulimall.com/list.html?" + link);
            }
            navs.add(navVo);
        }

        //TODO 分类：不要导航取消


        return result;
    }

    private String replaceQueryString(SearchParam param, String attr, String key) {
        String encode = null;
        try {
            encode = URLEncoder.encode(attr, "UTF-8");
            //当有空格时浏览器和java对此的差异化处理，java编译成‘+’，浏览器编译成'%20'
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String link = param.get_url().replace("&" + key + "=" + encode, "");
        return link;
    }

    /**
     * 封装es聚合返回的分类信息
     *
     * @param response
     * @param result
     */
    private void respAddCatalog(SearchResponse response, SearchResult result) {
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catalog_agg = response.getAggregations().get("catalog_agg");
        for (Terms.Bucket bucket : catalog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            if (!StringUtils.isEmpty(bucket.getKeyAsString())) {
                //得到分类id
                catalogVo.setCatalogId(Long.parseLong(bucket.getKeyAsString()));
                //获取【catalog_agg】聚合下的子聚合【catalog_name_agg】
                ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
                String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();
                catalogVo.setCatalogName(catalogName);
            } else {
                log.error("解析es返回聚合结果时，分类信息的id为空或为空字符串");
            }
            catalogVos.add(catalogVo);
        }
        result.setCatalogs(catalogVos);
    }

    /**
     * 封装es聚合返回的品牌信息
     *
     * @param response
     * @param result
     */
    private void respAddBrand(SearchResponse response, SearchResult result) {
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            //获取品牌id
            long brandId = bucket.getKeyAsNumber().longValue();
            //获取品牌名字
            String brandName = ((ParsedStringTerms) bucket.getAggregations().get("brand_name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            //获取品牌的图片
            String brandImg = ((ParsedStringTerms) bucket.getAggregations().get("brand_img_agg"))
                    .getBuckets().get(0).getKeyAsString();
            //设置品牌id
            brandVo.setBrandId(brandId);
            brandVo.setBrandName(brandName);
            brandVo.setBrandImg(brandImg);

            brandVos.add(brandVo);
        }
        result.setBrands(brandVos);
    }

    /**
     * 封装es聚合返回的attr信息
     *
     * @param response
     * @param result
     */
    private void respAddAttr(SearchResponse response, SearchResult result) {
        //获取attr_agg聚合
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        //获取attr_agg聚合字聚合attr_id_agg
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            //得到属性的id
            long attrId = bucket.getKeyAsNumber().longValue();
            //得到属性的名字
            String attrName = ((ParsedStringTerms) bucket.getAggregations().get("attr_name_agg"))
                    .getBuckets().get(0).getKeyAsString();
            //得到属性的值
            List<String> attrValues = ((ParsedStringTerms) bucket.getAggregations().get("attr_value_agg")).
                    getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).
                    collect(Collectors.toList());

            //设置值
            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }
        result.setAttrs(attrVos);
    }

    /**
     * 封装es聚合返回的商品信息
     *
     * @param result
     * @param hits
     */
    private void respAddProduct(SearchResult result, SearchHits hits, SearchParam param) {
        List<SKUEsModel> skuEsModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SKUEsModel skuEsModel = JSON.parseObject(sourceAsString, SKUEsModel.class);
                //判断是否需要高亮显示
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField highlightField = hit.getHighlightFields().get("skuTitle");
                    String skuTitle = highlightField.getFragments()[0].string();
                    skuEsModel.setSkuTitle(skuTitle);
                }
                skuEsModels.add(skuEsModel);
            }
        } else {
            log.error("解析es返回信息时，返回的信息为空，{}", hits.getHits());
        }
        result.setProducts(skuEsModels);
    }

    /**
     * 设置检索条件
     *
     * @param param
     * @param sourceBuilder
     */
    private void addSearchParam(SearchParam param, SearchSourceBuilder sourceBuilder) {
        //模糊匹配，过滤（按照属性、分类、价格区间、库存）
        //1 构建bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //1.1 must--模糊匹配
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", param.getKeyword()));
        }

        //1.2 bool - filter - 按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }

        //1.3 bool - filter - 按照品牌id查询
        if (param.getBrandId() != null) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }

        //1.4 bool - filter - 是否有库存
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        //1.5 bool - filter - 按照价格区间
        //TODO 价格区间有问题,代码实线没问题了????
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] priceRange = param.getSkuPrice().split("_");
            if (priceRange.length == 2) {
                rangeQuery.gte(priceRange[0]).lte(priceRange[1]);
            } else if (priceRange.length >= 1) {
                if (param.getSkuPrice().startsWith("_")) {
                    rangeQuery.lte(priceRange[0]);
                } else {
                    rangeQuery.gte(priceRange[0]);
                }
            } else {
                log.error("分割字符串错误,es查询时,前端传过来的[价格区间]字符串格式有误,价格区间:{}", param.getSkuPrice());
            }
            boolQuery.filter(rangeQuery);
        }

        //1.6 bool - filter - 按照所指定的属性进行查询
        if (!CollectionUtils.isEmpty(param.getAttrs())) {
            for (String attr : param.getAttrs()) {
                //分割出来id和具体的属性
                String[] s = attr.split("_");
                if (s.length > 0) {
                    String attrId = s[0];
                    //分割出来属性值
                    String[] attrValues = s[1].split(":");
                    if (attrValues.length > 0) {
                        //设置查询条件
                        BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                        nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                        nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                        //每一个都得生成一个嵌入式的查询
                        NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                        boolQuery.filter(nestedQuery);
                    } else {
                        log.error("分割字符串错误,es查询时,前端传过来的[属性值]字符串格式有误,属性值值:{}", attr);
                    }
                } else {
                    log.error("分割字符串错误,es查询时,前端传过来的[属性值]字符串格式有误,属性值值:{}", attr);
                }
            }
        }

        sourceBuilder.query(boolQuery);
    }

    /**
     * 进行排序
     *
     * @param param
     * @param sourceBuilder
     */
    private void searchSort(SearchParam param, SearchSourceBuilder sourceBuilder) {
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] sort = param.getSort().split("_");
            SortOrder sortOrder = sort[1].equals("asc") ? SortOrder.ASC : SortOrder.DESC;
            sourceBuilder.sort(sort[0], sortOrder);
        }
    }

    /**
     * 添加高亮
     *
     * @param param
     * @param sourceBuilder
     */
    private void addSearchHighlight(SearchParam param, SearchSourceBuilder sourceBuilder) {
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            //设置高亮显示的字段
            highlightBuilder.field("skuTitle");
            //设置前置标签
            highlightBuilder.preTags("<b style='color:red'>");
            //设置后置标签
            highlightBuilder.postTags("</b>");
            sourceBuilder.highlighter(highlightBuilder);
        }
    }

    private void addSearchAggregation(SearchSourceBuilder sourceBuilder) {
        //3.1 品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);
        //品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        sourceBuilder.aggregation(brand_agg);

        //3.2 分类聚合
        TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg").field("catalogId").size(20);
        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        sourceBuilder.aggregation(catalog_agg);

        //3.2 属性聚合,特殊处理
        NestedAggregationBuilder nested = AggregationBuilders.nested("attr_agg", "attrs");
        //聚合出attr_id_agg的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId").size(1);
        //聚合出attr_id_agg对应的attrName
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(20));
        nested.subAggregation(attr_id_agg);

        sourceBuilder.aggregation(nested);
    }
}
